# import pymysql
# # xlrd 为 python 中读取 excel 的库，支持.xls 和 .xlsx 文件
# import xlrd
#
# # openpyxl 库支持 .xlsx 文件的读写
# # from openpyxl.reader.excel import load_workbook
# # from builtins import int
#
#
# # cur 是数据库的游标链接，path 是 excel 文件的路径
# def importExcelToMysql(cur, path):
#     ### xlrd版本
#     # 读取excel文件
#     workbook = xlrd.open_workbook(path)
#     sheets = workbook.sheet_names()
#     worksheet = workbook.sheet_by_name(sheets[0])
#     ###
#
#     ### openpyxl版本
#     # 读取excel文件
#     # workbook = load_workbook(path)
#     # # 获得所有工作表的名字
#     # sheets = workbook.get_sheet_names()
#     # # 获得第一张表
#     # worksheet = workbook.get_sheet_by_name(sheets[0])
#     ###
#
#     ### xlrd版本
#     # 将表中数据读到 sqlstr 数组中
#     for i in range(1, worksheet.nrows):
#         row = worksheet.row(i)
#
#
#         sqlstr = []
#
#         for j in range(0, worksheet.ncols):
#             sqlstr.append(worksheet.cell_value(i, j))
#     ###
#
#     ### openpyxl版本
#     # 将表中每一行数据读到 sqlstr 数组中
#     # for row in worksheet.rows:
#     #
#     #     sqlstr = []
#     #
#     #     for cell in row:
#     #         sqlstr.append(cell.value)
#         ###
#
#         valuestr = [str(sqlstr[0]), int(sqlstr[1]), int(sqlstr[2]), int(sqlstr[3])]
#         print(valuestr)
#
#         # 将每行数据存到数据库中
#         cur.execute("insert into student(姓名, 语文, 数学, 英语) values(%s, %s, %s, %s)", valuestr)
#
#
# # 输出数据库中内容
# def readTable(cursor):
#     # 选择全部
#     cursor.execute("select * from student")
#     # 获得返回值，返回多条记录，若没有结果则返回()
#     results = cursor.fetchall()
#
#     for i in range(0, results.__len__()):
#         for j in range(0, 4):
#             print(results[i][j], end='\t')
#
#         print('\n')
#
#
# if __name__ == '__main__':
#     # 和数据库建立连接
#     conn = pymysql.connect('localhost', 'root', 'mysql', charset='utf8')
#     # 创建游标链接
#     cur = conn.cursor()
#
#     # 新建一个database
#     cur.execute("drop database if exists student")
#     cur.execute("create database student")
#     # 选择 students 这个数据库
#     cur.execute("use student")
#
#     # sql中的内容为创建一个名为student的表
#     sql = """CREATE TABLE IF NOT EXISTS `student` (
#                 `姓名` VARCHAR (20),
#                 `语文` INT,
#                 `数学` INT,
#                 `英语` INT
#               )"""
#     # 如果存在student这个表则删除
#     # cur.execute("drop table if exists student")
#     # 创建表
#     cur.execute(sql)
#
#     # 将 excel 中的数据导入 数据库中
#     importExcelToMysql(cur, "./student.xls")
#     # readTable(cur)
#
#     # 关闭游标链接
#     cur.close()
#     conn.commit()
#     # 关闭数据库服务器连接，释放内存
#     conn.close()
#     #     ---------------------
#     #     作者：Anwel
#     # 来源：CSDN
#     # 原文：https: // blog.csdn.net / Anwel / article / details / 79967261
#     # 版权声明：本文为博主原创文章，转载请附上博文链接！
#
# print("111")
# -*- coding:utf-8 -*-
# import re
# import pymysql
# from lxml import etree
# from selenium import webdriver
#
# __author__ = 'hp'
# __date__ = '2019/7/16 10:41'
#
# def test(ASIN):
#     url = f"https://www.amazon.com/dp/{ASIN}"
#     firefox_opt = webdriver.FirefoxOptions()
#     driver = webdriver.Firefox(firefox_options=firefox_opt)
#     driver.get(url)
#     print(ASIN)
#     color_imgs = eval(re.findall(r'"colorImages":(.*?),"heroImages"', driver.page_source)[0])
#     print(color_imgs)
#     img = list(color_imgs.values())[0][0]['large']
#     print(img)
#     return img
#
# class ImageToMysql(object):
#
#     def __init__(self):
#         self.url = ''
#         self.headers = ''
#
#     def counter_data(self,response_data):
#         """
#         数据提取与转换
#         [{"ImageUrl":"www.123123.com/1.jpg","ASIN":"7RW3SAF12QW"},....]
#         """
#
#         pass
#
#     def get_response_data(self,ASIN_LIST,cur,conn):
#
#         # 2 爬取数据
#         # data_of_list = []
#         for ASIN in ASIN_LIST:
#             # print(ASIN)
#             url = f"https://www.amazon.com/dp/{ASIN}"
#             print(url)
#             firefox_opt = webdriver.FirefoxOptions()
#             driver = webdriver.Firefox(firefox_options=firefox_opt)
#             try:
#                 driver.get(url)
#                 # content = re.findall(r'"colorImages":(.*?),"heroImages"', driver.page_source)
#                 response = etree.HTML(driver.page_source)
#                 img = response.xpath("//div[@id = 'imgTagWrapperId']/img/@src")
#                 driver.close()
#                 if img:
#                     good_img = img[0]
#                     print(good_img)
#                 else:
#                     good_img =  "http://25562m1t29.wicp.vip:39304/dist/no_img.jpg"
#             except:
#                 good_img = "http://25562m1t29.wicp.vip:39304/dist/no_img.jpg"
#             # data_of_list.append({"ASIN":ASIN,"ImageUrl":good_img})
#             self.data_to_mysql(cur=cur,data={"ASIN":ASIN,"ImageUrl":good_img},conn=conn)
#
#
#
#     def data_to_mysql(self, cur, data,conn):
#         "数据存入mysql"
#         i = data
#         sql = """UPDATE tb_order_items SET GoodsImage = '{}' WHERE ASIN = '{}'""".format(i['ImageUrl'], i['ASIN'])
#         print(sql)
#         cur.execute(sql)
#         conn.commit()
#
#
#     def get_mysql_data(self, cur):
#         sql = """SELECT ASIN FROM tb_order_items WHERE GoodsImage = '' ORDER BY ScheduledDeliveryEndDate"""
#         cur.execute(sql)
#         sql_data = cur.fetchall()
#         ASIN_LIST = list()
#         for i in sql_data:
#             ASIN_LIST.append(i[0])
#         return ASIN_LIST
#
#
# if __name__ == "__main__":
#
#
#
#         # 和数据库建立连接
#     conn = pymysql.connect('192.168.10.17', 'vne123', '123', charset='utf8')
#
#     # 创建游标
#     cur = conn.cursor()
#
#     # 选择数据库
#
#     cur.execute('use vnemy')
#
#
#
#     # 导入数据
#     # 1 创建对象
#
#     sfx = ImageToMysql()
#     # 获取AINS列表
#     ASIN_data = sfx.get_mysql_data(cur)
#     print(ASIN_data)
#
#
#     # 2 爬取数据
#     response = sfx.get_response_data(ASIN_data,cur=cur,conn=conn)
#
#     # 3 数据转换与提取
#     # data_list = sfx.counter_data(response)
#
#     # 4 将数据存入mysql
#     # sfx.data_to_mysql(cur,data=response,conn=conn)
#
#     cur.close()
#     # 关闭数据库服务器连接，释放内存
#     conn.close()


# def test():
#     a = 1
#     b = 2
#     return a,b
#
# c,d = test()
#
# print("%s,%s" % (c,d))
# import re
# #
# # result1 = """categoryList": "[{name=女装, id=10166}, {name=女式T恤, id=1031919}]"""
# # good_type = re.findall(r"name=([^,]*)", result1)
# # print(good_type)
#
# a = [1, 2, 3]
# print(str(a))
# demo = """{'categoryList': '[{name=女装, id=10166}, {name=女式T恤, id=1031919}]'}"""
# result = re.match(r"\[[^\]].*",demo)
# print(result)
# from django_redis import get_redis_connection
#
# redis = get_redis_connection('order_update_info')
# redis.delete('admin')
# coding:utf8
# register.py
# 功能说明：用户运行程序后，自动检测认证状态，如果未经认证，就需要注册。注册过程是用户将程序运行后显示的机器码（卷序号）发回给管理员，管理员通过加密后生成加密文件或字符串给回用户。
# 每次登录，在有注册文件或者注册码的情况下，软件就会通过DES和base64解码，如果解码后和重新获取的机器码一致，则通过认证，进入主程序。

# coding:utf8
# register.py
# 功能说明：用户运行程序后，自动检测认证状态，如果未经认证，就需要注册。注册过程是用户将程序运行后显示的机器码（卷序号）发回给管理员，管理员通过加密后生成加密文件或字符串给回用户。
# 每次登录，在有注册文件或者注册码的情况下，软件就会通过DES和base64解码，如果解码后和重新获取的机器码一致，则通过认证，进入主程序。
#
# import base64
# import win32api
#
# import wmi as wmi
# from pyDes import *
#
#
# # from binascii import a2b_hex    #如果需要用二进制编码保存注册码和注册文件可以使用binascii转换
#
# class register:
#     def __init__(self):
#         self.Des_Key = "BHC#@*UM"  # Key
#         self.Des_IV = "x22x33x35x81xBCx38x5AxE7"  # 自定IV向量
#
#     # 获取C盘卷序列号
#     # 使用C盘卷序列号的优点是长度短，方便操作，比如1513085707，但是对C盘进行格式化或重装电脑等操作会影响C盘卷序列号。
#     # win32api.GetVolumeInformation(Volume Name, Volume Serial Number, Maximum Component Length of a file name, Sys Flags, File System Name)
#     # return('', 1513085707, 255, 65470719, 'NTFS'),volume serial number is  1513085707.
#     def getCVolumeSerialNumber(self):
#         CVolumeSerialNumber = win32api.GetVolumeInformation("C:\\")[1]
#         # print chardet.detect(str(CVolumeSerialNumber))
#         # print CVolumeSerialNumber
#         if CVolumeSerialNumber:
#
#             return str(CVolumeSerialNumber)  # number is long type，has to be changed to str for comparing to content after.
#         else:
#             return 0
#
#     def getHardDiskNumber(self):
#         c = wmi.WMI()
#         print(c)
#         for physical_disk in c.Win32_DiskDrive():
#             print(physical_disk)
#             # return physical_disk
#
#     # 使用DES加base64的形式加密
#     # 考虑过使用M2Crypto和rsa，但是都因为在windows环境中糟糕的安装配置过程而放弃
#     def DesEncrypt(self, str):
#         k = des(self.Des_Key, CBC, self.Des_IV, pad=None, padmode=PAD_PKCS5)
#         EncryptStr = k.encrypt(str)
#         # EncryptStr = binascii.unhexlify(k.encrypt(str))
#         return base64.b64encode(EncryptStr)  # 转base64编码返回
#
#
#     # des解码
#     def DesDecrypt(self, str):
#         k = des(self.Des_Key, CBC, self.Des_IV, pad=None, padmode=PAD_PKCS5)
#         DecryptStr = k.decrypt(str)
#         # DecryptStr = a2b_hex(k.decrypt(str))
#         print
#         DecryptStr
#         return DecryptStr
#
#
#     # 获取注册码，验证成功后生成注册文件
#     def regist(self, key):
#         # key = raw_input('please input your register code: ')
#         # 由于输入类似“12”这种不符合base64规则的字符串会引起异常，所以需要增加输入判断
#         # while key
#         if key:
#             content = self.getCVolumeSerialNumber()
#
#             # print chardet.detect(content)
#             # print type(content)
#             # print content
#             # type(key_decrypted) is str
#             key_decrypted = str(self.DesDecrypt(base64.b64decode(key)))
#             # print chardet.detect(key_decrypted)
#             # print key_decrypted
#             # type(key_decrypted) is str
#             if content != 0 and key_decrypted != 0:
#                 if content != key_decrypted:
#                     print
#                     "wrong register code, please check and input your register code again:"
#                     self.regist()
#                 elif content == key_decrypted:
#                     print
#                     "register succeed."
#                     # 读写文件要加判断
#                     with open('./register', 'w') as f:
#                         f.write(key)
#                         f.close()
#                     return True
#                 else:
#                     return False
#             else:
#                 return False
#         else:
#             self.regist()
#         return False
#
#
#     def checkAuthored(self):
#         content = self.getCVolumeSerialNumber()
#         checkAuthoredResult = 0
#         # 读写文件要加判断
#         try:
#             f = open('./register', 'r')
#             if f:
#                 key = f.read()
#                 if key:
#                     key_decrypted = self.DesDecrypt(base64.b64decode(key))
#                     if key_decrypted:
#                         if key_decrypted == content:
#                             checkAuthoredResult = 1
#                         else:
#                             checkAuthoredResult = -1
#                     else:
#                         checkAuthoredResult = -2
#                 else:
#                     checkAuthoredResult = -3
#             else:
#                 self.regist()
#         except IOError:
#             print
#             IOError
#         print
#         checkAuthoredResult
#         return checkAuthoredResult
#
#
# if __name__ == '__main__':
#     reg = register()
#     str_num = reg.getCVolumeSerialNumber()
#     long_str = reg.getHardDiskNumber()
#     # print(long_str)
#     # print(str_num)

import base64
import random
import time
from datetime import datetime

import pymysql

now_time = datetime.now()
print(str(random.randint(0, 99999999)))
conn = pymysql.connect('192.168.10.17', 'vne123', '123', 'vnemy', charset='utf8',)

# 创建游标
cur = conn.cursor()
for i in range(10):
    time.sleep(1)
    str1 = base64.b64encode((str(random.randint(0,999999))+str(datetime.now())[-5:]+str(random.randint(0,999999))).encode()).decode()
    str1 = str1[:30]
    print(str1)

    # 选择数据库

    # cur.execute('use vnemy')
    # 4 将数据存入mysql
    # sfx.data_to_mysql(cur,data=response,conn=conn)
    sql = """insert into tb_register_code (register_code, status) values ('{}', 0)""".format(str1)
    cur.execute(sql)
    #
    # sql_data = cur.fetchall()
    # print(sql_data)


    # 关闭数据库服务器连接，释放内存
cur.close()
conn.close()
